package net.lgy.apitest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.lgy.apitest.model.DO.ApiTestResultDO;
import net.lgy.apitest.mapper.ApiTestResultMapper;
import net.lgy.apitest.service.ApiTestResultService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * API测试结果Service实现类
 */
@Service
public class ApiTestResultServiceImpl implements ApiTestResultService {

    @Autowired
    private ApiTestResultMapper apiTestResultMapper;

    @Override
    public ApiTestResultDO getById(Long id) {
        return apiTestResultMapper.selectById(id);
    }

    @Override
    public boolean save(ApiTestResultDO resultDO) {
        return apiTestResultMapper.insert(resultDO) > 0;
    }

    @Override
    public boolean removeById(Long id) {
        return apiTestResultMapper.deleteById(id) > 0;
    }

    @Override
    public List<ApiTestResultDO> getByAccountNo(Long accountNo) {
        LambdaQueryWrapper<ApiTestResultDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApiTestResultDO::getAccountNo, accountNo);
        // 使用id倒序排序代替不存在的createTime字段
        queryWrapper.orderByDesc(ApiTestResultDO::getId);
        return apiTestResultMapper.selectList(queryWrapper);
    }

    @Override
    public List<ApiTestResultDO> getByTestCaseId(Long testCaseId, Long accountNo) {
        LambdaQueryWrapper<ApiTestResultDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApiTestResultDO::getTestCaseId, testCaseId);
        queryWrapper.eq(ApiTestResultDO::getAccountNo, accountNo);
        // 使用id倒序排序代替不存在的createTime字段
        queryWrapper.orderByDesc(ApiTestResultDO::getId);
        return apiTestResultMapper.selectList(queryWrapper);
    }

    @Override
    public boolean batchRemoveByIds(List<Long> ids, Long accountNo) {
        LambdaQueryWrapper<ApiTestResultDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ApiTestResultDO::getId, ids);
        queryWrapper.eq(ApiTestResultDO::getAccountNo, accountNo);
        return apiTestResultMapper.delete(queryWrapper) > 0;
    }

    @Override
    public ApiTestResultDO getLatestByTestCaseId(Long testCaseId, Long accountNo) {
        LambdaQueryWrapper<ApiTestResultDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApiTestResultDO::getTestCaseId, testCaseId);
        queryWrapper.eq(ApiTestResultDO::getAccountNo, accountNo);
        // 使用id倒序排序代替不存在的createTime字段
        queryWrapper.orderByDesc(ApiTestResultDO::getId);
        queryWrapper.last("LIMIT 1");
        return apiTestResultMapper.selectOne(queryWrapper);
    }
}